package masterjava.common;

import masterjava.common.logging.ServerLogger;
import masterjava.common.shared.state.State;
import masterjava.common.shared.state.StateType;
import masterjava.common.util.Util;
import org.jetbrains.annotations.Nullable;

/**
 * User: GKislin
 * Date: May 26, 2010
 * <p/>
 * Base class for object with state
 */
abstract public class StateHolder {

    private final State state;
    private final ServerLogger logger = ServerLogger.get(getClass());

    public StateHolder() {
        this.state = new State();
    }

    public StateHolder(State state) {
        this.state = state;
    }

    public final void clearState() {
        state.clearState();
        logger.info("Clear state");
    }

    public final void set(String strState, Object... params) {
        setState(StateType.OK, strState, null, params);
    }

    public final void setWarning(String strState, Throwable e, Object... params) {
        setState(StateType.WARNING, strState, e, params);
    }

    public final void setError(final String strState, Throwable e, Object... params) {
        setState(StateType.ERROR, strState, e, params);
    }

    public final void setState(StateType type, String strState, @Nullable Throwable e, Object... params) {
        this.state.setState(type, Util.format(strState, params), e);
        logger.log(type.getLoggingLevel(), strState, e);
    }

    public State getState() {
        return state;
    }
}
